package cc.kzc.adminauth.config;

import java.util.Map;

import javax.persistence.EntityManager;
import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateProperties;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateSettings;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(entityManagerFactoryRef = "db1EntityManagerFactory", transactionManagerRef = "db1TransactionManager", basePackages = {
		"cc.kzc.adminauth.ds1" })
public class DB1Configurer {

	@Autowired
	@Qualifier("db1DataSource")
	private DataSource db1DataSource;

	@Autowired
	private JpaProperties jpaProperties;

	@Autowired
	private HibernateProperties hibernateProperties;

	private Map<String, Object> getVendorProperties() {
		return hibernateProperties.determineHibernateProperties(jpaProperties.getProperties(), new HibernateSettings());
	}

	// 创建实体类管理器工厂, 非主数据库不带@Primary
	@Primary
	@Bean(name = "db1EntityManagerFactory")
	public LocalContainerEntityManagerFactoryBean db1EntityManagerFactoryPrimary(EntityManagerFactoryBuilder builder) {
		return builder.dataSource(db1DataSource).properties(getVendorProperties()).packages("cc.kzc.adminauth.ds1")
				.persistenceUnit("db1PersistenceUnit").build();
	}

	// 创建实体类管理器, 非主数据库不带@Primary
	@Primary
	@Bean(name = "db1EntityManager")
	public EntityManager entityManager(EntityManagerFactoryBuilder builder) {
		return db1EntityManagerFactoryPrimary(builder).getObject().createEntityManager();
	}

	// 创建事务管理器, 非主数据库不带@Primary
	@Primary
	@Bean(name = "db1TransactionManager")
	public PlatformTransactionManager db1TransactionManager(EntityManagerFactoryBuilder builder) {
		return new JpaTransactionManager(db1EntityManagerFactoryPrimary(builder).getObject());
	}

}
